'use strict';

const os = require('os');
const colors = require('colors');
const restify = require('restify');
const CookieParser = require('restify-cookies');

process.on('uncaughtException', function (err) {
    console.error(err);
});

process.on('unhandledRejection', function(err, p) {
    console.error(err.stack);
});


let server = restify.createServer({
    name: 'demo_server',
});

server.use(restify.plugins.queryParser({mapParams: true}));  // req.query has the query
server.use(restify.plugins.bodyParser({     // parses json/x-www-form-urlencoded data to req.params
    maxBodySize: 5120,
    mapParams: true,
    mapFiles: false,
    overrideParams: false
}));
server.use(CookieParser.parse);


server.get('/greet', handleRequest);

async function handleRequest(req, res, next) {
    if (req.cookies) console.log('can get cookies'.green.bold);
    else console.log('no cookies'.red.bold);

    let screen = req.cookies['screen'];
    res.status(200);
    res.json({ success: true, host: os.hostname(), msg: screen || 'ERROR' });
    res.end();
}

server.pre((req, res, next) => {res.charSet('utf-8'); next()});

server.server.setTimeout(0);
server.listen(8888, async () => {
    console.log(`demo_server is listening on ${os.hostname()}:8888`);
});

